<template>
  <div class="container">
       <a-page-header
          title="系统权限管理"
        />
      <!-- 系统用户管理，查看用户列表，审核激活注册信息 -->
      <a-table :columns="columns" :data-source="data" class="table-container">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="customTitle"><a-icon type="smile-o" /> 用户名</span>
        <span slot="tag" slot-scope="tag">
          <a-tag
              :color="tag === false ? 'red' : 'green'"
          >
              {{ tag }}
          </a-tag>
        </span>
        <span slot="role" slot-scope="tag">
          <a-tag
              color="orange"
          >
              {{ roleMap[tag] }}
          </a-tag>
        </span>
        <span slot="action" slot-scope="record">
            <!-- {{record}} -->
            <a-button type="primary"  @click="getCredentialsInfo(record)">查看认证信息</a-button>
            &nbsp;&nbsp;
            <a-button type="primary"  @click="updateRole(record)" v-if="record.role != 'SYS_ADMIN'"> 权限变更</a-button>
        </span>
    </a-table>

    <!-- 更新权限对话框 -->
     <a-modal v-model="visible" title="权限变更" @ok="handleOk">
       <a-form :form="recordModal">
        <!-- 用户名 -->
        <a-form-item v-bind="formItemLayout" label="患者用户名">
              <a-input
              disabled
                v-decorator="[
                  'username',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
        <!-- 账户地址 -->
        <a-form-item v-bind="formItemLayout" label="患者用户名">
              <a-input
              disabled
                v-decorator="[
                  'accountAddress',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
        <!-- 变更权限 -->
        <a-form-item label="权限" has-feedback v-bind="formItemLayout">
          <a-select v-decorator="[
              'role',
              { rules: [{ required: true, message: 'place choice role!' }] },
            ]"
            placeholder="Please select a role">
            <a-select-option value="SYS_ADMIN">
              系统管理员
            </a-select-option>
            <a-select-option value="DOCTOR">
              医护人员
            </a-select-option>
            <a-select-option value="CLIENT">
              普通用户（患者）
            </a-select-option>
          </a-select>
        </a-form-item>
       </a-form>

    </a-modal>
  </div>
</template>

<script>
import {getAllUserInfo, activeUser, updateUserRole } from "@/api/user/user"

const columns = [
  {
    dataIndex: 'username',
    key: 'username',
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '电话',
    dataIndex: 'telephone',
    key: 'telephone',
  },
  {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
  },
  {
      title: '身份证号',
      dataIndex: 'identify',
      key: 'identify'
  },
  {
    title: '账户地址',
    dataIndex: 'accountAddr',
    key: 'accoutAddr',
  },
  {
    title: '账户状态',
    key: 'active',
    dataIndex: 'active',
    scopedSlots: { customRender: 'tag' },
  },
  {
    title: '角色权限',
    key: 'role',
    dataIndex: 'role',
    scopedSlots: { customRender: 'role' },
  },
  {
    title: 'Action',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];

// const data = [
//   {
//     key: '1',
//     username: 'alice',
//     accountAddr: '0xBe5f23A1d6bfB2913278A34CA159A2F9a2f61f36',
//     telephone: '14534645345',
//     email: '123@123.com',
//     identify: '4523432423123',
//     role: 'SYS_ADMIN',
//     active: true,
//   },
//   {
//     key: '2',
//     username: 'bob',
//     accountAddr: '0x66c026e6622e5111FD32c930E981F26Ffe99c3c5',
//     telephone: '14534645345',
//     email: '123@123.com',
//     identify: '4523432423123',
//     role: 'DOCTOR',
//     active: true,
//   },
//   {
//     key: '3',
//     username: 'ccc',
//     accountAddr: '0x1435F26C5e8fB8273233FF4C2A969d72A09c9954',
//     telephone: '',
//     email: '',
//     identify: '',
//     role: 'CLIENT',
//     active: false,
//   },
// ];

export default {
    data(){
        return {
            data: [],
            columns,
            roleMap: {
              'SYS_ADMIN':'系统管理员',
              'DOCTOR': "医生",
              "CLIENT": "普通用户"
            },
            visible: false,
            formItemLayout: {
              labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
              },
              wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
              },
            },
        }
    },
    methods: {
        updateRole(record){
           this.showModal(record)
        },
        getCredentialsInfo(record){
          if(record.credentials == "" || record.credentials == undefined){
            this.$message.info("该用户未提交认证信息")
          }else{
            // TODO，下载认证文件
            var url = "http://localhost:5002/ipfs/" + record.credentials
            console.log("link: ", url);
            let $body = document.body ;
            let link = document.createElement('a'); 
            link.style.display = 'none'; 
            $body.appendChild(link); 
            link.href = url //创建一个指向该参数对象的url
            link.target = "_blank"
            link.download = "cridential.doc";
            link.click(); // 触发下载
            $body.removeChild(link)
            link = null
          }
        },
        showModal(record) {
          this.visible = true;
          this.$nextTick(() => {
          this.recordModal.setFieldsValue({
            username: record.username,
            accountAddress: record.accountAddr,
            role: record.role
          })});
        },
        handleOk(e) {
          console.log(e);
          this.recordModal.validateFieldsAndScroll((err, values) => {
            if (!err) {
              console.log(values)
              updateUserRole(values)
              .then(data=>{
                this.$message.success("用户权限更新完成");
              })
              .catch(err=>{
                this.$message.error("更新用户权限出错")
              })
            }
          })

          this.visible = false;
        },
    },
    beforeCreate(){
       this.recordModal = this.$form.createForm(this, { name: 'recordModal' });
    },
     created(){
      // 获取所有用户信息
      getAllUserInfo()
      .then(data=>{
        var tData = []
          console.log("userinfo: ", data)
          for(var i = 0; i < data.data.length; i++){
            var t = {}
            var d = data.data[i]
            t['username'] = d[0];
            t['accountAddr'] = d[1];
            t['telephone'] = d[2];
            t['email'] = d[3];
            t['identify'] = d[4];
            t['role'] = d[5];
            t['active'] = d[6];
            t['credentials'] = d[8];
            tData.push(t)
          }
          this.data = tData;
      })
      .catch(err=>{
        console.log(err);
        this.$message.error("获取用户信息失败")
      })
    }
}
</script>

<style lang="less" scoped>
.container{
    margin: auto;
    width: 90%;
    min-height: 700px;
    // margin-top: 30px;
    margin-bottom: 30px;
    background-color: aliceblue;
}

.table-container{
    min-height: 700px;

}
</style>